/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imenu.terminal;

import java.io.*;
import java.net.*;
import java.util.*;

public class TerminalCommandServer extends ServerSocket {

    private static ArrayList userList = new ArrayList();
    private static ArrayList<ClientThread> clientThreads = new ArrayList<ClientThread>();
    //private static LinkedList Message_Array = new LinkedList();
    private static int threadCounter = 0;
    //private static boolean isClear = true;
    protected static final int SERVER_PORT = 7001;
    protected FileOutputStream LOG_FILE = new FileOutputStream("command.log", true);

    public TerminalCommandServer() throws IOException{
        super(SERVER_PORT);
    }
    public void startServer() throws FileNotFoundException, IOException {
        //new Broadcast().start();

        //append connection log 
        Calendar now = Calendar.getInstance();
        String str = "[" + now.getTime().toString() + "] Accepted a connection\015\012";
        byte[] tmp = str.getBytes();
        LOG_FILE.write(tmp);

        try {
            while (true) {
                Socket socket = accept();
                new ClientThread(socket).start();
            }
        } finally {
            close();
        }
    }

    public static void main(String[] args) throws IOException {
        new TerminalCommandServer().startServer();
    }

    /*
    class Broadcast extends Thread {

        public Broadcast() {
        }

        @Override
        public void run() {
            while (true) {
                if (!isClear) {
                    String tmp = (String) Message_Array.getFirst();

                    for (int i = 0; i < clientThreads.size(); i++) {
                        ClientThread client = (ClientThread) clientThreads.get(i);
                        client.sendMessage(tmp);
                    }

                    Message_Array.removeFirst();
                    isClear = Message_Array.size() > 0 ? false : true;
                }
            }
        }
    }
   */
//--- CreateServerThread 
    class ClientThread extends Thread {

        private Socket clientSocket;
        private BufferedReader in;
        private PrintWriter out;
        private String Username;

        public ClientThread(Socket s) throws IOException {
            clientSocket = s;
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            if(!"fangjia".equals((in.readLine()))){
                out.println("握手失败。");
                throw new IOException("握手失败。");
            }
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            //out.println("--- Welcome to this chatroom ---");
            //out.println("Input your nickname:");
        }

        public void sendMessage(String msg) {
            out.println(msg);
        }

        @Override
        public void run() {
            try {
                int flag = 0;
                threadCounter++;
                String line = in.readLine();

                while (!line.equals("bye")) {
                    if (line.equals("l")) {
                        out.println(listOnlineUsers());
                        line = in.readLine();
                        continue;
                    }

                    if (flag++ == 0) {
                        Username = line;
                        userList.add(Username);
                        out.println(listOnlineUsers());
                        clientThreads.add(this);
                       // pushMessage("[< " + Username + " come on in >]");
                    } else {
                        //pushMessage("<" + Username + ">" + line);
                    }

                    line = in.readLine();
                }

                //out.println("--- See you, bye! ---");
                clientSocket.close();
            } catch (IOException e) {
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                }

                threadCounter--;
                clientThreads.remove(this);
                userList.remove(Username);
                //pushMessage("[< " + Username + " left>]");
            }
        }

        private String listOnlineUsers() {
            String s = "-+- Online list -+-\015\012";

            for (int i = 0; i < userList.size(); i++) {
                s += "[" + userList.get(i) + "]\015\012";
            }

            s += "-+---------------------+-";
            return s;
        }

        //private void pushMessage(String msg) {
            //Message_Array.addLast(msg);
            //isClear = false;
        //}
    }
}
